package com.tange.ai.iot.client.gnssa.binding

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.util.Consumer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tange.ai.iot.client.gnssa.R
import com.tange.ai.iot.client.gnssa.databinding.ActivityAddApScanBinding
import com.tange.base.toolkit.Tips
import com.tange.base.ui.design.BasicDialogLoading
import com.tange.base.ui.design.BasicDialogRequest
import com.tange.feature.binding.connect.ap.DeviceBindingConnectionByAccessPoint
import com.tange.feature.binding.query.DeviceBindingQuery
import com.tange.feature.binding.search.DeviceBindingSearchAccessPoint
import com.tg.appcommon.android.TGLog

class BindingApScanActivity: AppCompatActivity() {

    companion object {
        const val TAG = "BindingApScanActivity_"
        const val CONFIG_REQ_CODE = 1001
    }

    private lateinit var binding: ActivityAddApScanBinding

    private lateinit var apSearch: DeviceBindingSearchAccessPoint

    private var apConnection: DeviceBindingConnectionByAccessPoint? = null

    private var bindingConfiguration = ""

    private var adapter: ApListAdapter? = null

    private var loading: BasicDialogLoading? = null

    private var bindingQuery: DeviceBindingQuery? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityAddApScanBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
        }

        com.tange.ai.iot.client.gnssa.utils.Utils.setStatusBar(this, Color.TRANSPARENT)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 100)
        }


        apSearch = DeviceBindingSearchAccessPoint(this) {
            TGLog.i(TAG, "[onSearched] $it")

            if (it.success) {
                adapter?.refreshApList(it.data)
            } else {
                binding.startScan.isEnabled = true
                Toast.makeText(this@BindingApScanActivity, "扫描失败: ${it.message}", Toast.LENGTH_LONG).show()
            }
        }

        binding.startScan.setOnClickListener {
            binding.startScan.isEnabled = false
            apSearch.start()
        }

        adapter = ApListAdapter()
        adapter?.onSelected = Consumer<String> { connectAndSend(it) }

        binding.apList.adapter = adapter
        binding.apList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        startActivityForResult(Intent(this, BindingConfigureActivity::class.java), CONFIG_REQ_CODE)
    }

    private fun connectAndSend(it: String) {
        if (TextUtils.isEmpty(bindingConfiguration)) {
            Toast.makeText(this@BindingApScanActivity, "绑定配置信息为空！", Toast.LENGTH_LONG).show()
            return
        }

        loading?.dismiss()
        loading = BasicDialogLoading(this).apply {
            setMessage("尝试连接设备并发送配网信息...")
        }
        loading?.show()

        if (apConnection != null) return

        apConnection = DeviceBindingConnectionByAccessPoint(this@BindingApScanActivity, it)
        apConnection?.sendAfterConnected(bindingConfiguration)  {
            loading?.dismiss()
            if (it.success) {
                Toast.makeText(this@BindingApScanActivity, "发送成功", Toast.LENGTH_LONG).show()
                queryBindingStatus()
            } else {
                Toast.makeText(this@BindingApScanActivity, "发送失败 ${it.code}, ${it.message}", Toast.LENGTH_LONG).show()

            }
        }
        Tips.show("由于系统限制，你需要手动点击连接")
    }

    private fun queryBindingStatus() {
        bindingQuery?.stop()
        bindingQuery = DeviceBindingQuery()
        bindingQuery?.duration = 120 * 1000L
        bindingQuery?.start(bindingConfiguration) {
            loading?.dismiss()

            if (it.success) {
                BasicDialogRequest(this@BindingApScanActivity).apply {
                    setMessage("绑定成功： 设备ID=${it.data}")
                    setPositiveText("知道了")
                    setPositiveOnClicked {
                        dismiss()
                        finish()
                    }
                }.show()
            } else {
                BasicDialogRequest(this@BindingApScanActivity).apply {
                    setMessage("绑定失败： ${it.code}, ${it.message}")
                    setPositiveText("知道了")
                    setPositiveOnClicked {
                        dismiss()
                        finish()
                    }
                }.show()
            }
        }


        if (loading?.isShowing == true) {
            loading?.dismiss()
        }

        loading = BasicDialogLoading(this).apply {
            setMessage("查询设备的绑定状态...")
        }
        loading?.show()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == CONFIG_REQ_CODE && RESULT_OK == resultCode) {
            bindingConfiguration = data?.getStringExtra(BindingConfigureActivity.CONFIG) ?: ""
        }

        if (requestCode == BindingBluetoothScanActivity.CONFIG_REQ_CODE && RESULT_CANCELED == resultCode) {
            Tips.show("必须生成绑定配置信息")
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        apSearch.stop()
        bindingQuery?.stop()
        apConnection?.destroy()
    }
}

class ApListAdapter : RecyclerView.Adapter<ViewHolder>() {
    private val apList: MutableList<String> = ArrayList()

    var onSelected: Consumer<String>? = null

    fun refreshApList(list: List<String>?) {
        apList.clear()
        list?.let { apList.addAll(it) }
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {
        val view: View = LayoutInflater.from(viewGroup.context).inflate(R.layout.item_scan_ap, viewGroup, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
        val apName = apList[position]
        viewHolder.textView.text = apName

        viewHolder.itemView.setOnClickListener { view: View ->
            onSelected?.accept(apName)
        }
    }

    override fun getItemCount(): Int {
        return apList.size
    }
}

class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    val textView: TextView

    init {
        textView = view.findViewById(R.id.ap_name)
    }
}